<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="../../lib/jquery-3.1.1.js" ></script>
		<style>
			button{background: #fff;border: 1px solid #cccccc;border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);color: #333;margin-left: 10px;height: 50px;line-height: 50px;padding: 0 20px;outline: none;font-size: 14px;cursor: pointer;}
			button.active{background-color: #1E9FFF;color: #fff;box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05);}
			button[disabled='disabled']{background-color: #dddddd;}
		</style>
	</head>
	<body>
		
		<p><button class="sku" attr_id="10">10</button><button class="sku" attr_id="11">11</button></p>
		<p><button class="sku" attr_id="20">20</button><button class="sku" attr_id="21">21</button><button class="sku" attr_id="22">22</button><button class="sku" attr_id="23">23</button><button class="sku" attr_id="24">24</button></p>
		<p><button class="sku" attr_id="30">30</button><button class="sku" attr_id="31">31</button><button class="sku" attr_id="32">32</button><button class="sku" attr_id="33">33</button><button class="sku" attr_id="34">34</button><button class="sku" attr_id="35">35</button><button class="sku" attr_id="36">36</button><button class="sku" attr_id="37">37</button><button class="sku" attr_id="38">38</button></p>
		<p><button class="sku" attr_id="40">40</button><button class="sku" attr_id="41">41</button></p>
        <p id="init_time"></p>
        <p id="price"></p>
        
		<script>
            /**
             * 该页面是从这里知道的
             * https://blog.csdn.net/rosanu_blog/article/details/49836575
             * /
			/* 后端数据 */
			var data = {};

			var startTime = new Date().getTime();
			//属性集
			var keys = [
		        ['10'],
		        ['20','21','22','23','24'],
		        ['30','31','32','33','34','35','36','37','38'],
		        ['40']
	        ];
			//保存最后的组合结果信息
			var SKUResult = {};
			
			//获得对象的key
			function getObjKeys(obj) {
			    if (obj !== Object(obj)) throw new TypeError('Invalid object');
			    var keys = [];
			    for (var key in obj)
			        if (Object.prototype.hasOwnProperty.call(obj, key))
			            keys[keys.length] = key;
			    return keys;
			}
			
			//把组合的key放入结果集SKUResult
			function add2SKUResult(combArrItem, sku) {
			    var key = combArrItem.join(";");
			    if(SKUResult[key]) {//SKU信息key属性·
			        SKUResult[key].count += sku.count;
			        SKUResult[key].prices.push(sku.price);
			    } else {
			        SKUResult[key] = {
			            count : sku.count,
			            prices : [sku.price]
			        };
			    }
			}
			
			//初始化得到结果集
			function initSKU() {
			    var i, j, skuKeys = getObjKeys(data);
                console.log(skuKeys)
			    for(i = 0; i < skuKeys.length; i++) {
			        var skuKey = skuKeys[i];//一条SKU信息key
			        var sku = data[skuKey]; //一条SKU信息value
                    var skuKeyAttrs = skuKey.split(";"); //SKU信息key属性值数组
			        skuKeyAttrs.sort(function(value1, value2) {
			            return parseInt(value1) - parseInt(value2);
			        });
			 
			        //对每个SKU信息key属性值进行拆分组合
			        var combArr = combInArray(skuKeyAttrs);
			        for(j = 0; j < combArr.length; j++) {
			            add2SKUResult(combArr[j], sku);
			        }
			 
			        //结果集接放入SKUResult
			        SKUResult[skuKeyAttrs.join(";")] = {
			            count:sku.count,
			            prices:[sku.price]
			        }
			    }
                console.log(SKUResult)
			}
			
			/**
			 * 从数组中生成指定长度的组合
			 * 方法: 先生成[0,1...]形式的数组, 然后根据0,1从原数组取元素，得到组合数组
			 */
			function combInArray(aData) {
				if(!aData || !aData.length) {
					return [];
				}
			
				var len = aData.length;
				var aResult = [];
			
				for(var n = 1; n < len; n++) {
					var aaFlags = getCombFlags(len, n);
					while(aaFlags.length) {
						var aFlag = aaFlags.shift();
						var aComb = [];
						for(var i = 0; i < len; i++) {
							aFlag[i] && aComb.push(aData[i]);
						}
						aResult.push(aComb);
					}
				}
				
				return aResult;
			}
			
			/**
			 * 得到从 m 元素中取 n 元素的所有组合
			 * 结果为[0,1...]形式的数组, 1表示选中，0表示不选
			 */
			function getCombFlags(m, n) {
				if(!n || n < 1) {
					return [];
				}
			
				var aResult = [];
				var aFlag = [];
				var bNext = true;
				var i, j, iCnt1;
			
				for (i = 0; i < m; i++) {
					aFlag[i] = i < n ? 1 : 0;
				}
			
				aResult.push(aFlag.concat());
			
				while (bNext) {
					iCnt1 = 0;
					for (i = 0; i < m - 1; i++) {
						if (aFlag[i] == 1 && aFlag[i+1] == 0) {
							for(j = 0; j < i; j++) {
								aFlag[j] = j < iCnt1 ? 1 : 0;
							}
							aFlag[i] = 0;
							aFlag[i+1] = 1;
							var aTmp = aFlag.concat();
							aResult.push(aTmp);
							if(aTmp.slice(-n).join("").indexOf('0') == -1) {
								bNext = false;
							}
							break;
						}
						aFlag[i] == 1 && iCnt1++;
					}
				}
				return aResult;
			} 

			
			//从数组中生成指定长度的组合
			function arrayCombine(targetArr) {
			    if(!targetArr || !targetArr.length) {
			        return [];
			    }
			 
			    var len = targetArr.length;
			    var resultArrs = [];
			 
			    // 所有组合
			    for(var n = 1; n < len; n++) {
			        var flagArrs = getFlagArrs(len, n);
			        while(flagArrs.length) {
			            var flagArr = flagArrs.shift();
			            var combArr = [];
			            for(var i = 0; i < len; i++) {
			                flagArr[i] && combArr.push(targetArr[i]);
			            }
			            resultArrs.push(combArr);
			        }
			    }
			     
			    return resultArrs;
			}
			
			
			//获得从m中取n的所有组合
			function getFlagArrs(m, n) {
			    if(!n || n < 1) {
			        return [];
			    }
			 
			    var resultArrs = [],
			        flagArr = [],
			        isEnd = false,
			        i, j, leftCnt;
			 
			    for (i = 0; i < m; i++) {
			        flagArr[i] = i < n ? 1 : 0;
			    }
			 
			    resultArrs.push(flagArr.concat());
			 
			    while (!isEnd) {
			        leftCnt = 0;
			        for (i = 0; i < m - 1; i++) {
			            if (flagArr[i] == 1 && flagArr[i+1] == 0) {
			                for(j = 0; j < i; j++) {
			                    flagArr[j] = j < leftCnt ? 1 : 0;
			                }
			                flagArr[i] = 0;
			                flagArr[i+1] = 1;
			                var aTmp = flagArr.concat();
			                resultArrs.push(aTmp);
			                if(aTmp.slice(-n).join("").indexOf('0') == -1) {
			                    isEnd = true;
			                }
			                break;
			            }
			            flagArr[i] == 1 && leftCnt++;
			        }
			    }
			    return resultArrs;
			}
			
			//初始化用户选择事件
			$(function() {
				$.get("data.json",function(res){
					data = res;
					initSKU();
				    var endTime = new Date().getTime();
				    $('#init_time').text('init sku time: ' + (endTime - startTime) + " ms");
				    $('.sku').each(function() {
				        var self = $(this);
				        var attr_id = self.attr('attr_id');
				        if(!SKUResult[attr_id]) {
				            self.attr('disabled', 'disabled');
				        }
				    }).click(function() {
				        var self = $(this);
				 
				        //选中自己，兄弟节点取消选中
				        self.toggleClass('active').siblings().removeClass('active');
				         
				        //已经选择的节点
				        var selectedObjs = $('.active');
				 
				        if(selectedObjs.length) {
				            //获得组合key价格
				            var selectedIds = [];
				            selectedObjs.each(function() {
				                selectedIds.push($(this).attr('attr_id'));
				            });
				            selectedIds.sort(function(value1, value2) {
				                return parseInt(value1) - parseInt(value2);
				            });
				            var len = selectedIds.length;
				            var prices = SKUResult[selectedIds.join(';')].prices;
				            var maxPrice = Math.max.apply(Math, prices);
				            var minPrice = Math.min.apply(Math, prices);
				            $('#price').text(maxPrice > minPrice ? minPrice + "-" + maxPrice : maxPrice);
				            //用已选中的节点验证待测试节点 underTestObjs
                            var int = 0
				            $(".sku").not(selectedObjs).not(self).each(function() { 
				                var siblingsSelectedObj = $(this).siblings('.active');
				                var testAttrIds = [];//从选中节点中去掉选中的兄弟节点
                                console.log(this)
                                console.log(siblingsSelectedObj)
				                if(siblingsSelectedObj.length) {
				                    var siblingsSelectedObjId = siblingsSelectedObj.attr('attr_id');
				                    for(var i = 0; i < len; i++) {
				                        if(selectedIds[i] != siblingsSelectedObjId) {
                                            testAttrIds.push(selectedIds[i])
                                        }
				                    }
				                } else {
				                    testAttrIds = selectedIds.concat();
				                }
				                testAttrIds = testAttrIds.concat($(this).attr('attr_id'));
				                testAttrIds.sort(function(value1, value2) {
				                    return parseInt(value1) - parseInt(value2);
				                });
				                if(!SKUResult[testAttrIds.join(';')]) {
				                    $(this).attr('disabled', 'disabled').removeClass('active');
				                } else {
				                    $(this).removeAttr('disabled');
				                }
				            });
				        } else {
				            //设置默认价格
				            $('#price').text('--');
				            //设置属性状态
				            $('.sku').each(function() {
				                SKUResult[$(this).attr('attr_id')] ? $(this).removeAttr('disabled') : $(this).attr('disabled', 'disabled').removeClass('active');
				            })
				        }
				    });
				});
			})
			
		</script>
	</body>
</html>
